package com.jboost.modules.message.service;

import cn.jiguang.common.ClientConfig;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
import com.jboost.config.JPushConfig;
import com.jboost.modules.message.entity.SysMessage;
import com.jboost.modules.message.handle.enums.SendMsgTypeEnum;
import com.jboost.modules.message.service.ISysMessageService;
import com.jboost.modules.system.util.JsonUtils;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @BelongsProject: preferential-treasure
 * @BelongsPackage: com.ruoyi.system.service
 * @Author: yefei
 * @CreateTime: 2022-01-12 12:07
 * @Description: 极光相关
 */
@Service
@RequiredArgsConstructor
public class JPushService {

    private final JPushConfig jPushConfig;
    private final ISysMessageService sysMessageService;

    /**
     * 推送消息
     *
     * @param title     消息标题
     * @param content   消息内容
     * @param extrasMap 额外参数
     * @param alias     设备别名（为空则所有用户都推送）
     */
    @SneakyThrows
    @Async
    public PushResult sendPush(String userId,String title, String content, Map<String, String> extrasMap, String... alias) {
        SysMessage sysMessage = new SysMessage();
        sysMessage.setEsReceiver(userId);
        sysMessage.setEsTitle(title);
        sysMessage.setEsContent(content);
        sysMessage.setEsParam(JsonUtils.toJson(extrasMap));
        sysMessage.setRemark(JsonUtils.toJson(alias));
        sysMessage.setEsType(SendMsgTypeEnum.APP.getType());
        //发送开始状态
        sysMessage.setEsSendStatus("0");
        sysMessageService.save(sysMessage);
        ClientConfig instance = ClientConfig.getInstance();
        instance.setTimeToLive(Long.parseLong(jPushConfig.getLiveTime()));
        JPushClient jPushClient = new JPushClient(jPushConfig.getMasterSecret(), jPushConfig.getAppkey(), null, instance);
        PushResult pushResult = jPushClient.sendPush(buildPushPayload(title, content, extrasMap, alias));
        if(pushResult.isResultOK()){
            sysMessage.setUpdateTime(new Date());
            sysMessage.setEsSendStatus("1");
            sysMessageService.updateById(sysMessage);
        }
        return pushResult;
    }

    private PushPayload buildPushPayload(String title, String content, Map<String, String> extrasMap, String... alias) {
        if (extrasMap == null || extrasMap.isEmpty()) {
            extrasMap = new HashMap<>();
        }
        // 批量删除数组中空元素
        String[] newAlias = removeArrayEmptyElement(alias);
        return PushPayload.newBuilder().setPlatform(Platform.android_ios())
                // 别名为空，全员推送；别名不为空，按别名推送
                .setAudience((null == newAlias || newAlias.length == 0) ? Audience.all() : Audience.alias(alias))
                .setNotification(Notification.newBuilder().setAlert(content)
                        .addPlatformNotification(
                                AndroidNotification.newBuilder().setTitle(title).addExtras(extrasMap).build())
                        .addPlatformNotification(IosNotification.newBuilder().incrBadge(1).addExtras(extrasMap).build())
                        .build())
                .build();
    }

    private String[] removeArrayEmptyElement(String... strArray) {
        if (null == strArray || strArray.length == 0) {
            return null;
        }
        List<String> strList = new ArrayList<>();
        for (String str : strArray) {
            // 消除空格后再做比较
            if (null != str && !"".equals(str.trim())) {
                strList.add(str);
            }
        }
        // 若仅输入"",则会将数组长度置为0
        return strList.toArray(new String[0]);
    }

}
